define( [ 
		'underscore', 
		'jquery',
		'backbone', 
		'view/bookview', 
		'model/book',
		'model/library',
	  	'jqueryui',	
	], 
function( _, $, Backbone, BookView, Book, Library ) {
	var LibraryView = Backbone.View.extend({
		el:$("#books"),
		// Using this anchor all works as expected
	
		// el:$("#bookShelf"),
		// this anchor breaks functionality of the add
		// dialog. However the event handlig gets broken,
		// while the bookshelf view is outside library view.

		initialize:function(){
			debugger;
			// this.collection = new Library(books);
			this.collection = new Library();
			this.collection.fetch();
			this.render();

			this.collection.on("add", this.renderBook, this);
			this.collection.on("remove", this.removeBook, this);
			this.collection.on("reset", this.render, this);

			// appCTX.bind('image:processed', this.processForm );
			// This pattern registers the message for the global object. 
			// This only works for methods without the reference to context 
			// (they do not contain this.data as the reference to
			// members of the object). Otherwise the listenTo should be used

			this.listenTo( appCTX, 'image:processed', this.processForm );
			// This pattern is binding the events triggered inside appCTX
			//  object into local object 'this'. appCTX is a global context
			//  object. It helps to transmit the messages for callback functions.
		},

		render:function(){
			var that = this;
			_.each(this.collection.models, function(item){
				that.renderBook(item);
			}, this);
		},

		renderBook:function(item){
			var bookView = new BookView({
				model:item
			});
			this.$el.append(bookView.render().el);
		},

		removeBook:function(removedBook){
			var removedBookData = removedBook.attributes;
			_.each(removedBookData, function(val, key){
				if(removedBookData[key] === removedBook.defaults[key]){
					console.log("collection: removing the default object");
					delete removedBookData[key];
				}
			});
	
			/*
			_.each(books, function(book){
				if(_.isEqual(book, removedBookData)){
					books.splice(_.indexOf(books, book), 1);
				}
			});
			*/
		},

		testMessage: function(e) {
			e.preventDefault();
			e.stopPropagation();
			console.log("LibraryView context");
			console.log(e);
		},

		events:{
			"click #yetAnotherAdd":"testMessage",
		}
	});
	return LibraryView;
});
